package cn.edu.zhku.aspect;

import cn.edu.zhku.aspect.annotation.Paging;
import cn.edu.zhku.aspect.enmu.DataType;
import cn.edu.zhku.dto.BaseDto;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PagingAspect extends BaseDtoAspect {

    @Value("${paging.group.default-page-num}")
    private Integer groupPageNum;
    @Value("${paging.group.default-page-size}")
    private Integer groupPageSize;
    @Value("${paging.task.default-page-num}")
    private Integer taskPageNum;
    @Value("${paging.task.default-page-size}")
    private Integer taskPageSize;
    @Value("${paging.form.default-page-num}")
    private Integer formPageNum;
    @Value("${paging.form.default-page-size}")
    private Integer formPageSize;
    @Value("${paging.user.default-page-num}")
    private Integer userPageNum;
    @Value("${paging.user.default-page-size}")
    private Integer userPageSize;

    @Pointcut("@annotation(cn.edu.zhku.aspect.annotation.Paging)")
    public void pointcut() {}

    @Before("baseDtoPointcut() && pointcut()")
    public void setPageNumAndPageSize(JoinPoint joinPoint) {
        Paging paging = ((MethodSignature)joinPoint.getSignature()).getMethod()
                .getAnnotation(Paging.class);
        BaseDto baseDto = (BaseDto) joinPoint.getArgs()[0];
        DataType type = paging.value();
        if (type == DataType.GROUP) {
            if (baseDto.getPageNum() == null) {
                baseDto.setPageNum(this.groupPageNum);
            }
            if (baseDto.getPageSize() == null) {
                baseDto.setPageSize(this.groupPageSize);
            }
        } else if (type == DataType.TASK) {
            if (baseDto.getPageNum() == null) {
                baseDto.setPageNum(this.taskPageNum);
            }
            if (baseDto.getPageSize() == null) {
                baseDto.setPageSize(this.taskPageSize);
            }
        } else if (type == DataType.FORM) {
            if (baseDto.getPageNum() == null) {
                baseDto.setPageNum(this.formPageNum);
            }
            if (baseDto.getPageSize() == null) {
                baseDto.setPageSize(this.formPageSize);
            }
        } else if (type == DataType.USER) {
            if (baseDto.getPageNum() == null) {
                baseDto.setPageNum(this.userPageNum);
            }
            if (baseDto.getPageSize() == null) {
                baseDto.setPageSize(this.userPageSize);
            }
        }
    }

}
